import { http } from '@/utils/request'
import { defineStore } from 'pinia'
import type { Profile } from '@/types'
import { message } from '@/components/XtxUI/Message'
import router from '@/router'

// const { target } = currenLink

// 导出时取名 use + 名称 + Store 这样的写法
// 下面写错了，由于太多地方就不改了，以后注意
export const member = defineStore('member', {
  persist: true,
  state: () => ({
    userInfo: {} as Profile,
    profile: {} as Profile,
  }),
  getters: {
    isLogin(): boolean {
      return !!this.userInfo.token
    },
  },
  actions: {
    // 登录成功后的调用
    loginSuccess() {
      const { target = '/' } = router.currentRoute.value.query
      message({ type: 'success', text: '登录成功！', time: 2000 })
      setTimeout(() => {
        // console.log(`output->target`, target)
        router.push(target as string)
      }, 1000)
    },
    // 登录请求
    async login(data: object) {
      const res = await http<Profile>('/login', 'post', data)
      this.userInfo = res.data.result
      this.loginSuccess()
    },
    logout() {
      // 清空用户信息
      this.userInfo = {} as Profile
      // 用户提示
      message({ type: 'success', text: '退出登录成功' })
    },
    // 三方登录_账号绑定  /login/social/bind
    async loginSocialBind(data: {
      unionId: string
      mobile: string
      code: string
    }) {
      // 发送请求
      const res = await http<Profile>('/login/social/bind', 'POST', data)
      // 能发送请求看到封装好的数据即可，因为验证码业务还没写，会报错
      console.log('loginSocialBind -----> ', res)
    },
    async sentCode(data: object) {
      const res = await http('/login/social/code', 'GET', data)
      console.log('sentCode', res)
    },
    // QQ直接登录
    async loginQQUnionId(data: { unionId: string; source: number }) {
      const res = await http<Profile>('/login/social', 'POST', data)
      // console.log("POST", "/login/social", res.data.result);
      this.profile = res.data.result
      this.loginSuccess()
    },
  },
})
